package com.atguigu.chapter03;

import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.java.functions.KeySelector;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.util.Collector;

/**
 * @Author lizhenchao@atguigu.cn
 * @Date 2021/6/8 10:21
 */
public class Flink01_Parallelism {
    public static void main(String[] args) throws Exception {
        System.out.println("xxxxxxxxxxxx");
        // 1. 获取流的执行环境
        Configuration conf = new Configuration();
        conf.setInteger("rest.port", 2000);
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(conf);
        env.setParallelism(3);
        env.disableOperatorChaining();
        // 2. 各种转换
        DataStreamSource<String> lineStream = env.socketTextStream("hadoop162", 9999);
        SingleOutputStreamOperator<Tuple2<String, Long>> resultStream = lineStream
            .flatMap(new FlatMapFunction<String, String>() {
                @Override
                public void flatMap(String line,
                                    Collector<String> collector) throws Exception {
                    for (String word : line.split(" ")) {
                        collector.collect(word);
                    }
                }
            })
            .map(new MapFunction<String, Tuple2<String, Long>>() {
                @Override
                public Tuple2<String, Long> map(String word) throws Exception {
                    return Tuple2.of(word, 1L);
                }
            })
//            .startNewChain()
//            .disableChaining()
            .filter(x -> true)
            .keyBy(new KeySelector<Tuple2<String, Long>, String>() {
                @Override
                public String getKey(Tuple2<String, Long> t) throws Exception {
                    return t.f0;
                }
            })
            .sum(1);
        
        // 3. 输出
        resultStream.print();
        
        // 4. 启动执行环境
        env.execute("Flink01_Parallelism");
    }
}
/*





如何给算子设置并行度:
 
 4种方式(优先级以此升高):
    1. 在配置文件中配置  flink-conf.yaml
        当提交应用的时候会自动读取并行度配置
        parallelism.default: 1
        
    2. 提交应有的实时进行配置
         bin/flink run -p 2  ...
         
    
    3. 在env中配置
        env.setParallelism(1);
        
    4. 单独给算子设置并行度
        map().setParallelism(2)
        
-----

禁用操作链:
1. .startNewChain()
    这个算子会重新将开启一个新的链
    
2. .disableChaining()
     当前算子不和任何算子chain在一起
     
3.  env.disableOperatorChaining();
    在整个job中禁用操作链
 */